package com.archive.forum.controller;

import com.archive.forum.mapper.ImageSha1Mapper;
import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.ImageSha1;
import com.archive.forum.model.ImageSha1Example;
import com.archive.forum.model.User;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ImageSha1Mapper imageSha1Mapper;
    @Transactional
    @PostMapping("/upload-image")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file,
                                           @RequestParam(value = "updateAvatar",defaultValue = "false")boolean updateAvatar,
                                           HttpServletRequest request) {
        try {
            // 1. 计算文件的 SHA1 码
            String fileSha1 = DigestUtils.sha1Hex(file.getInputStream());

            // 2. 检查数据库中是否已存在相同的 SHA1 码
            ImageSha1Example imageSha1Example= new ImageSha1Example();
            imageSha1Example.createCriteria().andSha1EqualTo(fileSha1);
            List<ImageSha1> imageSha1s= imageSha1Mapper.selectByExample(imageSha1Example);
            User accountUser = (User) request.getSession().getAttribute("user");
            ImageSha1 targetImageSha1; // 最终使用的图片记录
            if (imageSha1s.isEmpty()) {
                // 3. 生成唯一文件名
                String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

                // 4. 保存文件到指定目录
                String UPLOAD_DIR = "src/main/resources/static/images/upload/";
                Path uploadPath = Paths.get(UPLOAD_DIR + fileName);
                Files.createDirectories(uploadPath.getParent()); // 确保目录存在
                Files.copy(file.getInputStream(), uploadPath, StandardCopyOption.REPLACE_EXISTING);

                // 5. 插入图片信息到数据库
                ImageSha1 newImageSha1 = new ImageSha1();
                newImageSha1.setImageUrl("/images/upload/" + fileName);
                newImageSha1.setSha1(fileSha1);
                newImageSha1.setGmtCreate(System.currentTimeMillis());
                imageSha1Mapper.insert(newImageSha1);
                targetImageSha1 = newImageSha1; // 使用新插入的记录

            }else {
                targetImageSha1 = imageSha1s.get(0); // 使用已存在的记录
            }
            // 6. 更新用户头像路径（如果需要）
            if (updateAvatar && accountUser != null) {
                accountUser.setAvatarUrl(targetImageSha1.getImageUrl());
                userMapper.updateByPrimaryKeySelective(accountUser);

            }

            // 7. 构造响应数据
            Map<String, Object> response = new HashMap<>();
            Map<String, String> data = new HashMap<>();
            response.put("errno", 0);
            data.put("url", targetImageSha1.getImageUrl());
            data.put("alt", file.getOriginalFilename());
            response.put("updateAvatar", updateAvatar); // 返回是否更新头像的标志
            response.put("data", data);

            return response;


        } catch (IOException e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("errno", 1);
            errorResponse.put("message", e.getMessage());
            return errorResponse;
        }
    }
}
